package com.xssn.fjnd.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xssn.fjnd.entities.Member;
import com.xssn.fjnd.entities.Photo;
import com.xssn.fjnd.user.mapper.MemberMapper;
import com.xssn.fjnd.user.req.MemberREQ;
import com.xssn.fjnd.user.service.IMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xssn.util.aliyun.AliyunUtil;
import com.xssn.util.base.Result;
import com.xssn.util.properties.XssnOssProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 成员信息表 服务实现类
 * </p>
 *
 * @author 线狮少年
 * @since 2023-08-16
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements IMemberService {

    @Autowired
    private IMemberService memberService;


    @Override
    public Result queryPage(MemberREQ req) {
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        //根据演出图片标题（title）和演出图片状态（status）查询
        if (StringUtils.isNotEmpty(req.getNickName())) {
            wrapper.like("nick_name", req.getNickName());
        }
        if (req.getStatus() != null) {
            wrapper.eq("status", req.getStatus());
        }
        wrapper.orderByAsc("status").orderByDesc("update_date");
        //再进行分页
        IPage<Member> page = baseMapper.selectPage(req.getPage(), wrapper);
        List<Member> memberList = page.getRecords();
        for (Member member : memberList) {
            member.setAge(this.getAgeByBirth(member.getBirthDay()));
        }

        return Result.ok(page);
    }

    @Override
    public Result getMemberById(String id) {
        Member member = baseMapper.selectById(id);
        int MemberAge = this.getAgeByBirth(member.getBirthDay());
        member.setAge(MemberAge);
        return Result.ok(member);
    }

    @Transactional // 事务管理
    @Override
    public Result updateOrSave(Member member) {
        // 1. 如果id不为空，则是更新操作
        if(StringUtils.isNotEmpty(member.getId())) {
            // 更新：将更新时间设置当前时间
            member.setUpdateDate(new Date());
        }

        // 更新或保存演出图片信息（新增数据后，会将这条新增数据的主键id值放到id属性中）
        super.saveOrUpdate(member);

        // 返回演出图片id
        return Result.ok(member.getId());
    }


    @Autowired
    private XssnOssProperties xssnOssProperties;


    @Override
    public Result deleteById(String id) {
        Member member = baseMapper.selectById(id);
        String avatar = member.getAvatar();

        baseMapper.deleteById(id);

        //删除oss上的图片
        if(StringUtils.isNotEmpty(avatar)) {
            AliyunUtil.delete(avatar, xssnOssProperties.getAliyun());
        }
        return Result.ok();
    }

    @Override
    public Result getMemberList() {

        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("isjob", 1);

        //根据职位排序  ==》 0: 队长, 1：副队长，2：核心成员，3：正式成员，4：见习成员
        wrapper.orderByAsc("status").orderByAsc("create_date");
        List<Member> memberList = baseMapper.selectList(wrapper);
        for (Member member : memberList) {
            member.setAge(this.getAgeByBirth(member.getBirthDay()));
        }

        return Result.ok(memberList);
    }

    /**
     * 根据成员出生日期计算时间
     * @param birthDay
     * @return
     */
    private int getAgeByBirth(Date birthDay) {
        int age = 0;
        try {
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());// 当前时间

            Calendar birth = Calendar.getInstance();
            birth.setTime(birthDay);

            if (birth.after(now)) {//如果传入的时间，在当前时间的后面，返回0岁
                age = 0;
            } else {
                age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
                if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
                    age += 1;
                }
            }
            return age;
        } catch (Exception e) {//兼容性更强,异常后返回数据
            return 0;
        }
    }


}
